/*
 * Powered By cuichen
 * Since 2014 - 2016
 */
package com.seeyoui.kensite.framework.cms.article.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.seeyoui.kensite.bussiness.partybuild.job.AggregateJob;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.Result;
import com.seeyoui.kensite.common.util.SpringContextHolder;
import com.seeyoui.kensite.common.util.excel.ExportExcel;
import com.seeyoui.kensite.framework.cms.article.domain.Article;
import com.seeyoui.kensite.framework.cms.article.domain.ArticleVO;
import com.seeyoui.kensite.framework.cms.article.persistence.ArticleMapper;
import com.seeyoui.kensite.framework.cms.article.service.ArticleQueryService;
import com.seeyoui.kensite.framework.cms.article.service.ArticleService;
import com.seeyoui.kensite.framework.cms.category.service.CategoryService;
import com.seeyoui.kensite.framework.cms.portlet.domain.Portlet;
import com.seeyoui.kensite.framework.cms.portlet.service.PortletService;
import com.seeyoui.kensite.framework.cms.portletArticle.domain.PortletArticle;
import com.seeyoui.kensite.framework.cms.portletArticle.service.PortletArticleService;
import com.seeyoui.kensite.framework.cms.study.domain.Study;
import com.seeyoui.kensite.framework.cms.study.service.StudyService;
import com.seeyoui.kensite.framework.oa.applyActivity.domain.ApplyActivity;
import com.seeyoui.kensite.framework.oa.applyActivity.service.ApplyActivityService;
import com.seeyoui.kensite.framework.system.domain.SysUser;
import com.seeyoui.kensite.framework.system.util.UserUtils;

/**
 * 内容发布文章
 * 
 * @author cuichen
 * @version 2.0
 * @since 1.0
 * @date 2016-07-15
 */

@Controller
@RequestMapping(value = "cms/article")
public class ArticleController extends BaseController {

	@Autowired
	private ArticleService articleService;
	@Autowired
	private ArticleQueryService articleQueryService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private PortletService portletService;
	@Autowired
	private ApplyActivityService applyActivityService;
	@Autowired
	private StudyService studyService;
	@Autowired
	private PortletArticleService portletArticleService;

	/**
	 * 展示列表页面
	 * 
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("framework/cms/article/" + page, modelMap);
	}

	/**
	 * 根据ID查询单条数据
	 * 
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
			@PathVariable String id) throws Exception {
		Article article = articleService.findOne(id);
		return article;
	}

	/**
	 * 根据ID查询单条数据并返回相应表单
	 * 
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/form/{page}/{id}")
	public ModelAndView form(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page, @PathVariable String id) throws Exception {
		Article article = articleService.findOne(id);
		modelMap.put("article", article);
		return new ModelAndView("framework/cms/article/" + page, modelMap);
	}

	/**
	 * 获取列表展示数据
	 * 
	 * @param modelMap
	 * @param article
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list/data", method = RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Article article) throws Exception {
		List<Article> articleList = articleService.findList(article);
		int total = articleService.findTotal(article);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(articleList);
		return eudg;
	}

	/**
	 * 获取所有数据
	 * 
	 * @param modelMap
	 * @param article
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list/all", method = RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Article article) throws Exception {
		List<Article> articleList = articleService.findAll(article);
		return articleList;
	}

	/**
	 * 保存新增的数据
	 * 
	 * @param modelMap
	 * @param article
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpSession session, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap,
			Article article) throws Exception {
		if (!beanValidator(modelMap, article)) {
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		articleService.save(article);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 保存修改的数据
	 * 
	 * @param modelMap
	 * @param article
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public String update(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Article article) throws Exception {
		if (!beanValidator(modelMap, article)) {
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		articleService.update(article);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 保存修改的数据
	 * 
	 * @param modelMap
	 * @param article
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateContent", method = RequestMethod.POST)
	@ResponseBody
	public String updateContent(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Article article) throws Exception {
		if (!beanValidator(modelMap, article)) {
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		articleService.updateContent(article);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 删除数据库
	 * 
	 * @param modelMap
	 * @param articleId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		articleService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 导出Excel数据
	 * 
	 * @param modelMap
	 * @param article
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/export")
	public String export(HttpSession session, HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Article article) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		List<Article> articleList = articleService.findAll(article);
		new ExportExcel(null, Article.class).setDataList(articleList).write(response, fileName).dispose();
		return null;
	}

	/**
	 * 客户端页面数据展示 通过栏目id查询匹配的模块，查找文章，页面展示 （首页，两学一做，党建要闻）
	 * 
	 * @param categoryId
	 * @param model
	 * @return String
	 */
	@RequestMapping("/articleList")
	public String articleList(String categoryId, Model model) throws Exception {
		List<ArticleVO> articleList = articleQueryService.listArticleByCategoryId(categoryId);
		String indexUrl = categoryService.getUrlByCategoryId(categoryId);
		model.addAttribute("articleList", articleList);
		return indexUrl;
	}

	/**
	 * 三会一课页面数据展示 三会一课页面专用方法
	 * 
	 * @param categoryId
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/partyActivity")
	public String partyActivity(String categoryId, Model model) throws Exception {
		List<ArticleVO> articleList = articleQueryService.listArticleActivityByCategoryId(categoryId);
		String indexUrl = categoryService.getUrlByCategoryId(categoryId);
		List<ApplyActivity> activityList = applyActivityService.listPassNotStart();
		model.addAttribute("articleList", articleList);
		model.addAttribute("activityList", activityList);
		return indexUrl;
	}

	/**
	 * 跳转列表页面并传递模块id
	 * 
	 * @param portletId
	 * @param model
	 * @return
	 */
	@RequestMapping("/portletArticle")
	public String portletArticle(String portletId, Model model) {
		model.addAttribute("portletId", portletId);
		Portlet portlet = portletService.findOne(portletId);
		String removeStr1 = "模块";
		String removeStr2 = "首页";
		String portletName = portlet.getName().replace(removeStr1, "").replace(removeStr2, "");
		model.addAttribute("portletName", portletName);
		return "partybuild/list_more";
	}

	/**
	 * 列表页面数据请求方法
	 * 
	 * @param portletId
	 * @param model
	 * @param page
	 * @param rows
	 * @return
	 */
	@RequestMapping("/portletArticle/list")
	@ResponseBody
	public Object portletArticle(String portletId, Model model, int page, int rows, ArticleVO articleVO)
			throws Exception {
		articleVO.setPage(page);
		articleVO.setRows(rows);
		articleVO.setPortletId(portletId);
		List<ArticleVO> articleList = articleQueryService.listArticleByPortletId(articleVO);
		/*
		 * Portlet portlet = portletService.findOne(portletId); String removeStr1 =
		 * "模块"; String removeStr2 = "首页"; String portletName =
		 * portlet.getName().replace(removeStr1, "") .replace(removeStr2, "");
		 */
		// Long total = (long) articleList.size();
		PortletArticle portletArticle = new PortletArticle();
		portletArticle.setPortletId(articleVO.getPortletId());
		int total = portletArticleService.findTotal(portletArticle);
		Page<Article> pageInfo = new Page<Article>(page, rows, total);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("rows", articleList);
		dataMap.put("page", pageInfo);
		return dataMap;
	}

	/**
	 * 文章详情，app端接口
	 * 
	 * @param articleId
	 * @return
	 */
	@RequestMapping(value = "/articleDetailMob", method = RequestMethod.POST)
	@ResponseBody
	public Result findArticleById(String articleId) {
		// / TODO 根据用户id及文章id查询是否点赞，后续版本增加此功能
		/*
		 * SysUser sysUser = UserUtils.getUser(request); Study study =
		 * studyService.findStudyByUserIdAndArticleId(sysUser.getId(), articleId);
		 */
		Article article = articleService.findOne(articleId);
		return Result.success(article);
	}

	/**
	 * 文章详情，仅用于PC端
	 * 
	 * @param id
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/articleDetail")
	public String articleDetail(String id, Model model, HttpServletRequest request) throws Exception {
		Article article = articleService.findOne(id);
		model.addAttribute("article", article);
		SysUser sysUser = UserUtils.getUser(request);
		Study study = studyService.findStudyByUserIdAndArticleId(sysUser.getId(), id);
		if (study != null) {
			model.addAttribute("praise", study.getPraise());
		}
		return "partybuild/detail";
	}

	/**
	 * 点赞 传入用户id，文章id
	 * 
	 * @param request
	 * @param articleId
	 * @return
	 */
	@RequestMapping(value = "/praise", method = RequestMethod.POST)
	@ResponseBody
	public Result praise(HttpServletRequest request, String articleId, String praise) {
		SysUser sysUser = UserUtils.getUser(request);
		Study study = studyService.findStudyByUserIdAndArticleId(sysUser.getId(), articleId);
		ArticleMapper articleMapper = SpringContextHolder.getBean(ArticleMapper.class);
		if ("1".equals(praise)) {
			study.setPraise("0");
			studyService.update(study);

			articleMapper.updatePraiseByAggregate();

			return Result.failure("取消点赞");
		} else {
			if (study == null) {
				Study newStudy = new Study();
				newStudy.setUserId(sysUser.getId());
				newStudy.setArticleId(articleId);
				newStudy.setPraise("1");
				newStudy.setDuration("0");
				studyService.save(newStudy);
			} else {
				study.setPraise("1");
				studyService.update(study);
			}

			articleMapper.updatePraiseByAggregate();

			return Result.success("", "点赞成功");
		}
	}

	/**
	 * 手机端两学一做接口
	 * 
	 * @param pageIndex
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/partyStudyApp")
	@ResponseBody
	public Result listPartyStudyApp(Integer pageIndex) throws Exception {
		List<ArticleVO> articleList = articleQueryService.listArticleByPortletIdApp(pageIndex);
		if (!articleList.isEmpty()) {
			return Result.success(articleList);
		} else {
			return Result.failure("查询失败");
		}
	}

	/**
	 * 党建要闻、十九大
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/partyBuildNews")
	@ResponseBody
	public Result listPartyBuildNews(Integer type) {
		List<ArticleVO> articleList = new ArrayList<ArticleVO>();
		if (type == 1) {
			articleList = articleQueryService.listArticleByCategoryId("00c8ebea171649c9a4dd7bd0c46983d7");
			articleList = (List<ArticleVO>) getRandomList(articleList, 10);// 随机抽取10条
		} else if (type == 2) {
			articleList = articleQueryService.listArticleByCategoryId("115dfe4026704b36af2df32290727ca0");
			articleList = (List<ArticleVO>) getRandomList(articleList, 10);// 随机抽取10条
		}
		if (articleList.isEmpty()) {
			return Result.failure("暂无数据");
		} else {
			return Result.success(articleList);
		}
	}

	/**
	 * 三会一课、党员活动接口
	 * 
	 * @param type
	 * @return
	 */
	@RequestMapping("/partyActive")
	@ResponseBody
	public Result partyActivityApp(Integer type) {
		ApplyActivity applyActivity = applyActivityService.findLastActivity(type);
		if (applyActivity != null) {
			return Result.success(applyActivity);
		} else {
			return Result.failure("查询失败");
		}
	}

	/**
	 * 三会一课、党员活动更多接口 近期、往期
	 * 
	 * @param type
	 * @param state
	 * @return
	 */
	@RequestMapping("/partyActiveMore")
	@ResponseBody
	public Result partyActivityMoreApp(Integer type, Integer state) {
		List<ApplyActivity> activityList = applyActivityService.listTypeAndState(type, state);
		if (!activityList.isEmpty()) {
			return Result.success(activityList);
		} else {
			return Result.failure("查询失败");
		}
	}

	/**
	 * 根据id查询党员活动详情 查询申请表详情
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/partyActiveDetail")
	@ResponseBody
	public Result findPartyActiveDetailById(String id) {
		ApplyActivity applyActivity = applyActivityService.findOne(id);
		if (applyActivity != null) {
			return Result.success(applyActivity);
		} else {
			return Result.failure("查询失败");
		}
	}

	/**
	 * 三会一课党员活动会议纪要
	 * 
	 * @param type
	 * @return
	 */
	@RequestMapping("/summaryList")
	@ResponseBody
	public Result listSummaryApp(Integer type) {
		List<ArticleVO> articleList = articleQueryService.listSummary(type);
		if (!articleList.isEmpty()) {
			return Result.success(articleList);
		} else {
			return Result.failure("查询失败");
		}
	}

	/**
	 * 三会一课、党员活动会议纪要接口
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/summaryDetail")
	@ResponseBody
	public Result summaryDetail(String id) {
		ArticleVO article = articleQueryService.findArticleDetailById(id);
		if (article != null) {
			return Result.success(article);
		} else {
			return Result.failure("查询失败");
		}
	}

	/**
	 * @function:从list中随机抽取若干不重复元素
	 *
	 * @param paramList:被抽取list
	 * @param count:抽取元素的个数
	 * @return:由抽取元素组成的新list
	 */
	public static List<?> getRandomList(List<?> paramList, int count) {
		if (paramList.size() < count) {
			return paramList;
		}
		Random random = new Random();
		List<Integer> tempList = new ArrayList<Integer>();
		List<Object> newList = new ArrayList<Object>();
		int temp = 0;
		for (int i = 0; i < count; i++) {
			temp = random.nextInt(paramList.size());// 将产生的随机数作为被抽list的索引
			if (!tempList.contains(temp)) {
				tempList.add(temp);
				newList.add(paramList.get(temp));
			} else {
				i--;
			}
		}
		return newList;
	}

}